<template>
    <div class="flexWrap">
        <div class="demand-content">
            <div class="sep-view">
                <div class="sep-title">
                    <i class="iconfont demand sep-icon"></i>需求
                </div>
                <div v-if="!detail.id" class="flexWrap" style="margin-left: 250px">
                    <el-button size="mini" style="margin-right: 20px" type="text" @click="toClose">关 闭</el-button>
                    <el-button size="mini" type="text" @click="toSubmit">保 存</el-button>
                </div>
            </div>
            <div class="c-item">
                <el-input :disabled="detail.disabled.title" size="small" v-model="detail.title" placeholder="需求标题" class="c-right" @blur="demandInfoOnChange('title')"/>
            </div>
            <div class="c-item">
                <rich-txt :disabled="detail.disabled.detail" size="small" :content="detail.detail"
                          placeholder="需求详情" class="c-right" style="height: calc(100vh - 280px); padding-bottom: 50px"
                          @complete="demandInfoOnChange('detail')" @change="richTxtOnChange" />
            </div>
            <div class="c-item">
                <el-radio-group v-model="detail.status" @change="demandInfoOnChange('status')">
                    <el-radio class="p-radio" size="mini"
                              v-for="v in statusAry" :label="v.v"
                              :disabled="detail.disabled.status[v.v]"
                    ><span style="font-weight: normal">{{v.n}}</span></el-radio>
                </el-radio-group>
            </div>
            <div class="c-item">
                <el-radio-group v-model="detail.p" :disabled="detail.disabled.p" @change="demandInfoOnChange('p')">
                    <el-radio class="p-radio" size="mini"
                              v-for="v in pAry"
                              :label=v.v
                    ><span :style="{ 'font-weight': 'normal', color: v.c }">{{v.n}}</span></el-radio>
                </el-radio-group>
            </div>
            <div class="c-item flexWrapBetween">
                <el-date-picker :disabled="detail.disabled.deadline" @change="demandInfoOnChange('deadline')"
                                style="width: 140px;" placeholder="选择日期" value-format="yyyy-MM-dd"
                                v-model="detail.deadline" type="date">
                </el-date-picker>
                <el-select style="width: 120px;" size="mini" :disabled="detail.disabled.leader" @change="demandInfoOnChange('leader')"
                           v-model="detail.leader">
                    <el-option v-for="u in userAry" :key=u.id :label=u.name :value=u.id />
                </el-select>
                <el-select style="width: 140px;" size="small" @change="demandInfoOnChange('projectId')"
                           v-model="detail.projectId" :disabled="detail.disabled.project"
                           placeholder="请选择">
                    <el-option v-for="u in projectAry" :key=u.id :label=u.name :value=u.id />
                </el-select>
            </div>
        </div>

        <div class="job-content">
            <div class="sep-view">
                <div class="sep-title mr-30">
                    <i class="iconfont job sep-icon"></i>任务
                </div>
                <template>
                    <el-button type="primary" plain size="mini" icon="el-icon-circle-plus" class="mini-el" style="margin: 5px 0;transform:scale(0.75)" @click="toAddJob(false)">添加</el-button>
                    <el-button type="primary" plain size="mini" icon="el-icon-circle-plus" class="mini-el" style="margin: 5px 0;transform:scale(0.75)" @click="toAddJob(true)">默认任务</el-button>
                </template>
            </div>
            <div class="c-item" style="margin-bottom: 100px">
                <div class="flexWrap c-right">
                    <div class="flexWrap w-per100">
                        <job-item v-for="(info, idx) in detail.jobs" :info="info" :id="idx" @delete="jobOnDel(idx)"/>
                    </div>
                </div>
            </div>
        </div>

        <div class="chat-content" id="chat-content-list">
            <div class="sep-view">
                <div class="sep-title ml-30">
                    <i class="iconfont chat sep-icon"></i>沟通
                </div>
<!--                <div style="transform: scale(0.80)" class="tCenter">-->
<!--                    <el-tabs size-mini v-model="chatStatus" type="card" @tab-click="chatStatusChanged">-->
<!--                        <el-tab-pane label="全部" name=0></el-tab-pane>-->
<!--                        <el-tab-pane label="需求阶段" name=1></el-tab-pane>-->
<!--                        <el-tab-pane label="开发阶段" name=2></el-tab-pane>-->
<!--                        <el-tab-pane label="测试阶段" name=3></el-tab-pane>-->
<!--                    </el-tabs>-->
<!--                </div>-->
            </div>
            <div class="chat-list">
                <div class="flexWrap">
                    <div class="no-next" v-if="chats.length > 0 && chatPaging.haNext == false">已加载所有记录</div>
                    <div class="no-next" v-if="chats.length === 0">暂无沟通记录</div>
                    <chat-item v-for="v in chats" :info="v" :id="v.scrollId ? v.scrollId : null" />
                </div>
            </div>
            <div class="chat-buttons">
                <el-input class="input" type="textarea" :rows="4" v-model="chatContent" id="chat-txt-input" />
                <div class="buttons flexWrapBetween">
                    <div>
                        <el-button type="text" size="mini" @click="toAddChatFile(20)">附件</el-button>
                        <el-button type="text" size="mini" @click="toAddChatFile(11)">链接</el-button>
                    </div>
                    <el-button type="primary" size="mini" @click="toAddChatTxt">发送</el-button>
                </div>
            </div>
        </div>

        <!--聊天-->
        <el-dialog v-if="chat.show" :visible=true width="630px" append-to-body border :show-title=false :show-close=false>
            <chat-edit :info="chat.info" @complete="chatOnAdd" />
        </el-dialog>

        <!--任务-->
        <el-dialog :visible.sync="job.show" width="550px" append-to-body border :show-title=false :show-close=false>
            <job-edit v-if="job.show" :info="job.info" @complete="jobOnAdd" />
        </el-dialog>
    </div>
</template>
<script>
import JobItem from "@/views/job/components/jobItem"
import JobEdit from "@/views/job/components/jobEdit"
import ChatItem from "@/views/chat/components/chatItem";
import ChatEdit from "@/views/chat/components/chatEdit";
import RichTxt from "@/components/richTxt/richTxt"
export default {
    name: "demand",
    props: {
        info: {
            type: Object
        },
        complete: {
            type:Function
        }
    },
    data() {
        return {
            statusAry: [{n:'确认中',v:1},{n:'开发中',v:20},{n:'开发完成',v:100},{n:'已上线',v:110},{n:'已废弃',v:-1}],
            pAry: [{n:"P0急",v:1, c:"#F56C6C"},{n:"P1高",v:2, c:"#E6A23C"},{n:"P2一般",v:3, c:"#67C23A"},{n:"P3低",v:4, c:"#909399"}],

            filter: {
                keyword:""
            },

            detail: {
                id: '', name:"", resources:[], disabled:{status:{}}
            },
            me:{id:0},
            userAry:[],
            projectAry:[],

            job: {show:false, info: {}},
            case: {show:false, info: {}},

            chatStatus:0,
            chats: [],
            chatContent:"",
            chatPaging: {size:20, lastId:0, fetchingId:'', haNext:true},
            chat: {show:false, info: {}},

            lastChatTxtKey: '',
        };
    },
    components: {
        RichTxt,
        JobItem,JobEdit,ChatItem,ChatEdit
    },
    created() {
        let acc = this.auth.getAccount()
        this.me = {id:acc.id, name: acc.name, roles:acc.roles}

        this.userAry = this.consts.users()
        this.projectAry = this.consts.projects()

        this.detail = this.format.demand(this.info)
        if (this.detail.id) {
            this.fetchDetail()
            this.fetchChats()
        }

        setTimeout(() => {
            let _this = this
            document.getElementById("chat-txt-input").addEventListener("keydown", function (e) {
                if (e.key === 'Alt' || e.key === 'Control' || e.key === 'Meta') {
                    _this.lastChatTxtKey = "Alt"
                } else if (e.key === 'Enter') {
                    if (_this.lastChatTxtKey === 'Alt') {
                        if (_this.chatContent !== "") {
                            //换行
                            _this.chatContent += "\n"
                        } else {
                            //发送
                            _this.toAddChatTxt()
                        }
                    } else {
                        //发送
                        _this.toAddChatTxt()
                    }
                } else {
                    _this.lastChatTxtKey = ''
                }

            },false)
            document.getElementById("chat-txt-input").addEventListener("keyup", function (e) {
                if (e.key !== 'Enter') {
                    _this.lastChatTxtKey = ''
                }
            },false)

            document.getElementById("chat-content-list").addEventListener('scroll', this.onScroll, true)
        },200)
    },
    methods: {
        toClose() {
            this.$emit("complete");
        },

        demandInfoOnChange(k) {
            this.$forceUpdate()
            if (!this.detail.id) return

            let orgValue = ""
            if (k == 'status' || k == "p") {
                orgValue = this.detail[k]
            }

            let value = ""
            if (k == 'projectId' || k == 'leader' || k == 'title' || k == 'status' || k == 'p' || k == 'detail') {
                value = this.detail[k] + ""
            } else if (k == 'deadline') {
                if (this.detail.deadline) {
                    value = this.utils.timeStr(this.detail.deadline, "Y-M-D")
                } else {
                    value = ''
                }
            } else if (k == 'partners') {
                for (let i = 0; i < this.detail.users.length; i++) {
                    value += this.detail.users[i] + ","
                }
            }
            this.request.post({
                url: "demand.update", data: {demandId:this.detail.id, key:k, value:value}
            }).then(res => {
                this.$forceUpdate()
            },res => {
                this.detail[k] = orgValue
                this.$forceUpdate()
                this.$message.error(res.msg || '保存失败');
            })
        },
        richTxtOnChange(e) {
            this.detail.detail = e.html
        },

        toEditResource(e) {
            this.resource = {show:true, info:{demandId:this.detail.id}}
        },
        resourceOnAdd(e) {
            if (!this.detail.resources) this.detail.resources = []
            if (e) this.detail.resources.push(e)
            this.resource.show = false
        },
        resourceOnDel(idx) {
            let item = this.detail.resources[idx]
            item.status = -1
            if (item.id > 0) {
                this.request.post({
                    url:"demand.resource.update", data: {resourceId:item.id, key: 'status', value:'-1'}
                }).then( res => {
                    this.detail.resources.splice(idx,1)
                    this.$forceUpdate()
                }, res => {
                    this.$message.error(res.msg || "删除失败");
                })
            } else {
                this.detail.resources.splice(idx,1)
            }
        },


        toAddJob(isDefault) {
            if (!isDefault) {
                this.job = {show:true, info:{demandId:this.detail.id, fromDemand:true}}
            } else {
                if (!this.detail.p || !this.detail.status || !this.detail.deadlineStr) {
                    this.$message.error({message:"请先完善需求", duration:800});
                    return
                }

                this.job = {
                    show:true, info:{
                        fromDemand:true, isDefault:true,
                        content: this.detail.title,
                        demandId:this.detail.id, status:1, p:this.detail.p, deadlineStr:this.detail.deadlineStr,
                    }
                }
                this.job.info.deadline = this.utils.timeStr(this.job.info.deadlineStr, "Y-M-D") + " 00:00:00"
            }
        },
        jobOnAdd(e) {
            if (!this.detail.jobs) this.detail.jobs = []
            if (e) this.detail.jobs.push(e)
            this.job.show = false
            this.$forceUpdate()

        },
        jobOnDel(idx) {
            this.detail.jobs.splice(idx,1)
        },


        toAddChatTxt() {
            if (!this.chatContent)  return
            let s = this.chatContent
            s = s.replaceAll(" ", "")
            s = s.replaceAll("\n", "")
            s = s.replaceAll("\t", "")
            if (s === '') return;

            let item = {
                content: this.chatContent,
                resources:[],
                demandId: this.detail.id,
                demandStatus: this.detail.status,
                level: 1,
                status:1,
                creator: this.me.id,
                createAtStr: '刚刚',
                scrollId: 'scrollId-' + new Date().getTime()
            }

            this.toSaveChat(item)
            this.chatContent = ""
        },
        toAddChatFile(type) {
            this.chat = {show:true, info:{demandId:this.detail.id, type:type}}
        },
        toSaveChat(item) {
            if (!this.detail.id) {
                this.chats.push(this.format.chat(item))
                setTimeout(() => {
                    let ele = document.getElementById(item.scrollId)
                    if (ele) {
                        ele.scrollIntoView()
                    }
                },100)
            } else {
                item.demandId = this.detail.id
                this.request.post({
                    url:"demand.chat.save", data: item
                }).then( res => {
                    this.chatContent = ""

                    if (this.chatStatus != this.detail.status) {
                        if (this.chatStatus != 0 && (this.detail.status == 1 || this.detail.status == 2 || this.detail.status == 3)) {
                            if (res.result.type == 10 || res.result.type == 11) this.chatContent = ''
                            this.chatStatus = this.detail.status + ''
                            this.chatStatusChanged()
                            return
                        }
                    } else if (this.chatStatus != 0 && !(this.detail.status == 1 || this.detail.status == 2 || this.detail.status == 3)) {
                        if (res.result.type == 10 || res.result.type == 11) this.chatContent = ''
                        this.chatStatus = '0'
                        this.chatStatusChanged()
                        return
                    }

                    let v = this.format.chat(res.result)
                    v.scrollId = item.scrollId
                    this.chats.push(v)
                    setTimeout(() => {
                        let ele = document.getElementById(v.scrollId)
                        if (ele) {
                            ele.scrollIntoView()
                        }

                        if (v.type == 10 || v.type == 11) this.chatContent = ''
                    },100)
                    this.$forceUpdate()
                }, res => {
                    this.$message.error("发送失败");
                })
            }
        },

        chatOnAdd(e) {
            if (!this.chats) this.chats = []
            if (e) this.chats.push(e)
            this.chat.show = false
            this.$forceUpdate()
        },
        chatOnDel(idx) {
            let item = this.detail.chats[idx]
            item.status = -1
            if (item.id > 0) {
                this.request.post({
                    url:"demand.chat.update", data: {chatId:item.id, key: 'status', value:'-1'}
                }).then( res => {
                    this.detail.chats.splice(idx,1)
                    this.$forceUpdate()
                }, res => {
                    this.$message.error(res.msg || "删除失败");
                })
            } else {
                this.detail.chats.splice(idx,1)
            }
        },

        onScroll (e) {
            let scrollTop = e.target.scrollTop;
            if (scrollTop < 30) {
                this.fetchChats()
            }
        },

        toSubmit() {
            let params = {...this.detail}
            params.chats = this.chats

            if (!params.title) {this.$message.error('需求标题不能空'); return}
            if (!params.projectId) {this.$message.error('项目不可空'); return}

            if (params.p) params.p = parseInt(params.p)

            params.partners = ""
            if (params.users) {
                for (let i = 0; i < params.users.length; i++) {
                    params.partners += params.users[i] + ","
                }
            }

            if (params.jobs) {
                for (let i = 0; i < params.jobs.length; i++) {
                    let job = params.jobs[i]
                    if (job.deadlineStr) job.deadline = this.utils.timeStr(job.deadlineStr, "Y-M-D") + " 00:00:00"
                    if (job.status) job.status = parseInt(job.status)

                    job.partners = ""
                    if (job.users) {
                        for (let j = 0; j < job.users.length; j++) {
                            job.partners += job.users[i] + ","
                        }
                    }
                }
            }

            this.request.post({
                url: "demand.add", data: params
            }).then(res => {
                if (!params.id) this.toClose()
                this.$message.success({duration:1000, message:"保存成功"});
            },res => {
                this.$message.error(res.msg || '保存失败');
            })
        },

        chatStatusChanged(e) {
            this.chats = []
            this.chatPaging = {size:20, lastId:0, fetchingId:'', haNext:true}
            this.fetchChats()
        },

        fetchChats() {
            if (!this.chatPaging.haNext || !this.info.id) return
            if (this.chatPaging.lastId === this.chatPaging.fetchingId) return;
            this.chatPaging.fetchingId = this.chatPaging.lastId
            this.request.get({
                url: "demand.chat.list", data: {
                    demandId:this.info.id, size:this.chatPaging.size, lastId:this.chatPaging.lastId,
                    demandStatus: this.chatStatus,
                }
            }).then(res => {
                setTimeout(() => {
                    this.chatPaging.lastId = res.result.lastId
                },200)

                let list = res.result.list
                this.chatPaging.haNext = false
                if (list) {
                    this.chatPaging.haNext = list.length >= this.chatPaging.size

                    for (let i = 0; i < list.length; i++) {
                        this.format.chat(list[i])
                        list[i].scrollId = (i + 1) + '-chat-list'
                    }

                    if (this.chats.length === 0 && list.length > 0) {
                        let lastScrollId = list[list.length - 1].scrollId
                        setTimeout(() => {
                            let ele = document.getElementById(lastScrollId)
                            if (ele) {
                                ele.scrollIntoView()
                            }
                        },100)
                    }

                    if (this.chats.length > 0) { list.push(...this.chats) }
                    this.chats = list
                }
            },res => {
                this.$message.error(res.msg || '获取数据失败');
            })
        },

        fetchDetail() {
            if (!this.detail.id) {
                this.detail.editable = true
                this.detail.statusEditable = true
                return
            }

            this.request.get({
                url: "demand", data: {id:this.info.id}
            }).then(res => {
                this.detail = this.format.demand(res.result)

                let isManager = false
                let isDev = false
                let isTester = false
                for (let i = 0; i < this.me.roles.length; i++) {
                    if (this.me.roles[i] == 1 || this.me.roles[i] == 2) {
                        isManager = true
                    } else if (this.me.roles[i] == 4) {
                        isDev = true
                    } else if (this.me.roles[i] == 5) {
                        isTester = true
                    }
                }
                for (let i = 0; i < this.statusAry.length; i++) {
                    if (isManager || this.me.id == this.detail.creator) {
                        this.statusAry[i].disabled = false
                    } else if (isDev) {
                        this.statusAry[i].disabled = this.statusAry[i].v != 2 && this.statusAry[i].v != 3 && this.statusAry[i].v != 4 && this.statusAry[i].v != 5
                    } else if (isTester) {
                        this.statusAry[i].disabled = this.statusAry[i].v != 3 && this.statusAry[i].v != 4 && this.statusAry[i].v != 5
                    }
                }
            },res => {
                this.$message.error(res.msg || '获取数据失败');
            })
        },

    },
};
</script>
<style scoped lang="scss">
.sep-view {
    display: flex; height: 40px;

    .sep-title {
        margin-top: 10px;
        width: 60px; height: 20px; line-height: 20px; background-color: #CCECFF;
        font-size: 12px; font-weight: bold; text-align: center; border-radius: 4px; color: #1b9aee;

        .sep-icon {margin-right: 5px; font-size: 12px;}
    }
}


.demand-content {
    width: 450px; height: 100vh;  padding-left: 20px;
    overflow-y: scroll; -webkit-overflow-scrolling: touch; overflow-scrolling: touch;

    .c-title { width: 95%; }

    .c-item {
        width: 95%; margin: 10px 0 0 0; line-height: 20px;
        display: flex; flex-direction: row;

        .c-left {
            width: 80px; color: #aaaaaa; font-size: 13px; line-height: 30px;
        }
        .c-right {
            line-height: 30px; width: 100%; text-align: left;
        }
        .p-radio {
            line-height: 30px; margin: 0 20px 0 0;
        }
    }

    .c-division {margin: 30px 0 10px 0; width: 100%; font-size: 14px; font-weight: bold; color: #333333}


    .demand-buttons {
        position: fixed; bottom: 0; right: 600px; width: 200px; height: 30px; padding: 5px 0;
    }
}
.demand-content::-webkit-scrollbar{display: none}
.demand-content {-ms-overflow-style: none; scrollbar-width: none;}

.job-content {
    width: 430px; height: 100vh;
    background-color: #fafdfd;
}

.chat-content {
    width: 475px; height: calc(100vh - 100px); padding: 0 0 100px 0;
    text-align: left;

    .filter { margin: 20px 0 10px 25px; }

    .chat-list {
        margin: 0 15px; width: calc(100% - 30px); height: calc(100vh - 200px);
        overflow-y: scroll; -webkit-overflow-scrolling: touch; overflow-scrolling: touch; -ms-overflow-style: none; scrollbar-width: none;

        .chat-item {
            width: 100%;

            .name {

            }
            .content {
                width: 100%;
            }
        }

        .no-next {width: 100%; line-height: 20px; font-size: 11px; color: #cccccc; text-align: center}
    }
    .chat-list::-webkit-scrollbar{display: none}

    .chat-buttons {
        position: fixed; right:0; bottom: 0; width: 490px; height: 140px; background-color: white;

        .input {
            border: 0; width: 100%; line-height: 20px; font-size: 13px; text-align: left;
        }
        .buttons {
            margin: 10px 20px 0 20px;

            .btn {}
        }
    }
}


/*element ui 样式更新*/

.el-input.is-disabled /deep/ .el-input__inner {
    color: #333333;
    background-color: white;
}


</style>
